package com.totoro.tyrank.utils;

import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;

/**
 * 解析PAPI变量的工具类
 * @author TOTORO
 * @date 2024/8/29 14:18
 */
public class PapiUtil {

    public static String parseStrPapiVariable(Player player, String text) {
        return parseStrPapiVariable(player, text, false);
    }

    public static String parseStrPapiVariable(Player player, String text, Boolean isNotNumberAddSymbol) {
        char[] textChars = text.toCharArray();
        List<Integer> allPapiSymbolIndexList = new ArrayList<>();

        for (int i = 0; i < textChars.length; i++) {
            if(textChars[i] == '%') {
                allPapiSymbolIndexList.add(i);
            }
        }

        List<List<Integer>> splitList = ListUtil.splitList(allPapiSymbolIndexList, 2);

        List<PAPIData> papiList = new ArrayList<>(splitList.size());
        for (List<Integer> list : splitList) {
            String papiStr = text.substring(list.get(0), list.get(1) + 1);
            String placeholders = PlaceholderAPI.setPlaceholders(player, papiStr);
            if (isNotNumberAddSymbol) {
                // 解析值如果不是数字构成，则添加 ''
                if (!placeholders.matches("\\d+")) {
                    placeholders = "'" + placeholders + "'";
                }
            }
            papiList.add(new PAPIData(papiStr, placeholders));
        }

        for (PAPIData papi : papiList) {
            text = text.replaceAll(papi.getOriginalPapi(), papi.getReplacePapi());
        }
        return ColorUtil.color(text);
    }

    static class PAPIData {
        private String originalPapi;
        private String replacePapi;

        public PAPIData(String originalPapi, String replacePapi) {
            this.originalPapi = originalPapi;
            this.replacePapi = replacePapi;
        }

        public PAPIData() {
        }

        public String getOriginalPapi() {
            return originalPapi;
        }

        public void setOriginalPapi(String originalPapi) {
            this.originalPapi = originalPapi;
        }

        public String getReplacePapi() {
            return replacePapi;
        }

        public void setReplacePapi(String replacePapi) {
            this.replacePapi = replacePapi;
        }
    }
}
